package cn.samehope.pet.interceptor;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;

/**
 * 微信授权拦截器
 * @author LD
 *
 */
public class WxInterceptor implements Interceptor{

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		HttpServletRequest request = controller.getRequest();
		
		String open_id_session = controller.getSessionAttr("open_id_session");
		
		if(StrKit.isBlank(open_id_session)){
			
			String code_wx = request.getParameter("code");
			if(StrKit.isBlank(code_wx)){
				String getRequestURL =request.getRequestURL().toString();
			    String queryurl=request.getQueryString();
				if(null!=queryurl){
					getRequestURL += "?" + queryurl;
				}
				
				//String url = PropKit.get("openIdUrl").replace("APPID", PropKit.get("appId")).replace("URLDOMAIN", getRequestURL);
				String appid = ApiConfigKit.getApiConfig().getAppId();
			  	String state = "";
			  	String callbackUrl = getRequestURL;
				String url = SnsAccessTokenApi.getAuthorizeURL(appid, callbackUrl, state, false);
				try {
					controller.getResponse().sendRedirect(url);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				 String code = request.getParameter("code");
				 String state = request.getParameter("state");
				 if (code!=null) {
				      String appId = ApiConfigKit.getApiConfig().getAppId();
				      String secret = ApiConfigKit.getApiConfig().getAppSecret();
				      //通过code换取网页授权access_token
				      SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId,secret,code);
//				      String json=snsAccessToken.getJson();
				      String token = snsAccessToken.getAccessToken();
				      String openId = snsAccessToken.getOpenid();
				      controller.setSessionAttr("open_id_session", openId);
				      //拉取用户信息(需scope为 snsapi_userinfo)
				  }
			}
		}
		
		inv.invoke();
	}

}
